#!/usr/bin/env python
# -*- coding: utf-8 -*-
from urllib.parse import urlencode
import logging
import requests
from .appsvrapi import AppServerApi, APIReservation, APIBase, APIBase1

__author__ = 'raptor'

logger = logging.getLogger(__name__)


class JSApi(object):
    BACKEND_ROOT = None
    HOSPITAL_ID = None
    MSG_TEMPLATE = None

    def __init__(self, session):
        self.session = session
        self.user_id = session.get("user_id")
        # self.user_id = "0000727006"
        self.openid = session.get("openid")
        self.access_token = session.get("access_token")
        self.app_api = AppServerApi()
        self.push_api = APIBase()
        self.reservation_api = APIReservation()
        self.other_api = APIBase1()

    @staticmethod
    def get_instance(session, apitype=""):
        openid = session.get('openid')
        if apitype == "weixin" or openid:
            return JSApiWeixin(session)
        return None


class JSApiWeixin(JSApi):
    APPID = None
    APPSECRET = None
    URL_CALLBACK = None
    URL_AUTHORIZE = 'https://open.weixin.qq.com/connect/oauth2/authorize'
    URL_ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token'
    API = None
    CHANNEL = 'wx_pub'
    KEEP_ALIVE = False

    CLIENT = None

    def __init__(self, session):
        super().__init__(session)
        self.openid = session.get('openid')
        # self.openid = 'ovr-_w0neAnl9cq3ZY3yXVSXSj6s'
        self.unionid = session.get('unionid')

    def get_authorize_url(self):
        params = dict(appid=self.APPID, redirect_uri=self.URL_CALLBACK, response_type="code", scope="snsapi_base")
        return "#".join(["?".join([self.URL_AUTHORIZE, urlencode(sorted(params.items()))]), "wechat_redirect"])

    def get_authorize_url_by_callback(self, redirect_uri):
        params = dict(appid=self.APPID, redirect_uri=redirect_uri, response_type="code", scope="snsapi_base")
        return "#".join(["?".join([self.URL_AUTHORIZE, urlencode(sorted(params.items()))]), "wechat_redirect"])

    def get_access_token(self, code):
        params = dict(appid=self.APPID, secret=self.APPSECRET, code=code, grant_type="authorization_code")
        if JSApiWeixin.KEEP_ALIVE:
            if not JSApiWeixin.CLIENT:
                JSApiWeixin.CLIENT = requests.session()
            client = JSApiWeixin.CLIENT
            headers = None
        else:
            client = requests
            headers = {'Connection': 'close'}
        result = client.get("?".join([self.URL_ACCESS_TOKEN, urlencode(sorted(params.items()))]),
                            headers=headers).json()
        if not result.get("errcode", None):
            self.access_token = result['access_token']
            self.openid = result['openid']
            self.unionid = None
            # self.unionid = result['unionid']
            self.session['access_token'] = result['access_token']
            self.session['openid'] = result['openid']
            # session['unionid'] = result['unionid']
            return None
        else:
            return result['errmsg']

    def _get_user(self):
        return self.app_api.GET_user_weixin(openid=self.openid)

    def _check_auth(self):
        if not self.openid:
            self.session['errmsg'] = "失败，请在微信中打开"
            return False
        return True

    def _put_login(self, user_id):
        return self.app_api.PUT_user_weixin(user_id=user_id, openid=self.openid,
                                            unionid=self.unionid)

    def _put_logout(self):
        return self.app_api.PUT_user_weixin(user_id=self.user_id, openid=None,
                                            unionid=None)
